<template>
  <view class="change-password">
    <uni-forms ref="formRef" :model="formData" :rules="rules">
      <uni-forms-item label="原密码" name="oldpass">
        <uni-easyinput
          type="password"
          v-model="formData.oldpass"
          placeholder="请输入原密码"
        />
      </uni-forms-item>
      
      <uni-forms-item label="新密码" name="newpass">
        <uni-easyinput
          type="password"
          v-model="formData.newpass"
          placeholder="请输入新密码"
        />
      </uni-forms-item>
      
      <uni-forms-item label="确认密码" name="confpass">
        <uni-easyinput
          type="password"
          v-model="formData.confpass"
          placeholder="请再次输入新密码"
        />
      </uni-forms-item>
      
      <button class="submit-btn" @click="handleSubmit">确认修改</button>
    </uni-forms>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { FormInstance } from '@dcloudio/uni-ui'
import { handleModifyPassword, ModifyPasswordParams } from '@/api/sign'
import { ResponseResult } from '@/utils/request'

interface FormData {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

const formRef = ref<FormInstance>()
const formData = reactive<ModifyPasswordParams>({
  oldpass: '',
  newpass: '',
  confpass: ''
})

const rules = {
  oldpass: {
    rules: [{
      required: true,
      errorMessage: '请输入原密码'
    }]
  },
  newpass: {
    rules: [{
      required: true,
      errorMessage: '请输入新密码'
    }, {
      minLength: 6,
      errorMessage: '密码长度不能少于6位'
    }]
  },
  confpass: {
    rules: [{
      required: true,
      errorMessage: '请再次输入新密码'
    }, {
      validateFunction: function(rule: any, value: string, data: ModifyPasswordParams) {
        if (value !== data.newpass) {
          return '两次输入的密码不一致'
        }
        return true
      }
    }]
  }
}

const handleSubmit = async () => {
  try {
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (valid) {
      // TODO: 调用修改密码API
      handleModifyPassword(formData).then((res: ResponseResult) => {
        if (res && res.status == 1) {
          uni.showToast({
            title: '密码修改成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/my/index'
            })
          }, 1500)
        }
      })
      
    }
  } catch (err) {
    console.error(err)
  }
}
</script>

<style lang="scss" scoped>
.change-password {
  padding: 30rpx;
}
</style>